<template>
  <div>
    <el-row>
      <el-col :span="9">
        <el-button type="primary" :disabled="!hasPerm('system:roleModule:add')" size="mini" @click="addRoleModuleDialog=true">添加模块</el-button>
        <el-button type="primary" :disabled="!hasPerm('system:roleModule:addSon')" size="mini" @click="isCheck ? addSonRoleModuleDialog = true: open('请选择上级')">子级模块</el-button>
        <el-button type="primary" :disabled="!hasPerm('system:roleModule:delete')" size="mini" @click="roleModuleDelFun">删除模块</el-button>
        <el-button type="primary" :disabled="!hasPerm('system:roleModule:edit')" size="mini" @click="isCheck ? editRoleModuleDialog = true: open('请选择模块')">编辑模块</el-button>
        <el-card class="box-card" shadow="never" body-style="padding: 5px;" >
          <span style="font-size: 6px">当前选择：{{checkRoleModule.name}}</span>
        </el-card>
        <el-input
            placeholder="输入关键字进行过滤"
            v-model="filterRoleModuleText"
            size="mini"
            style="width: 350px;">
        </el-input>
        <el-tree style="margin: 5px 0px" :filter-node-method="filterRoleModuleNode" ref="roleModuleTree"
                 :expand-on-click-node="false"
                 :data="roleModuleData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
      </el-col>
      <el-col :span="1">
        <el-divider direction="vertical" class="el-divider--vertical"></el-divider>
      </el-col>
      <el-col :span="14">
        <template v-if="isCheck">
          <el-button type="primary" size="mini" @click="isCheck ? addRoleDialog=true:open('请选择模块')">添加角色</el-button>
          <el-table
              :data="roleData"
              style="width: 100%">
            <el-table-column
                label="名称"
                width="130"
                prop="name">
            </el-table-column>
            <el-table-column
                label="状态"
                width="130"
                :formatter="stateFormat">
              <template slot-scope="scope">
                <el-tag
                    :type="scope.row.status === '0' ? 'danger' : 'success'"
                    disable-transitions>{{scope.row.status === '0' ? '冻结' : '正常'}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
                label="备注"
                width="180">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p>{{ scope.row.remark }}</p>
                  <div slot="reference" class="name-wrapper">
                    {{ scope.row.remark && scope.row.remark.substr(0,15) }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-edit" @click.native="editRoleDialog=true;editRole=scope.row">详情</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-lock" @click.native="freezeRoleFun(scope.$index, scope.row)">冻结/解冻</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-s-custom" @click.native="openRoleUserDrawer(scope.row)">角色用户</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-key" @click.native="openRoleAclTree(scope.row)">角色权限</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-delete" @click.native="delRoleFun(scope.$index, scope.row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.pageNo"
              :page-sizes="[5, 10, 20]"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total">
          </el-pagination>
        </template>
        <el-empty v-else description="请选择角色模块"></el-empty>
      </el-col>
    </el-row>
    <el-dialog
        title="新增角色"
        :visible.sync="addRoleDialog"
        width="40%"
        center
        :before-close="handleClose">
      <el-form class="form" ref="addRole" :model="addRole" :rules="rules" :label-width="labelWidth">
        <el-form-item label="所属模块">
          <el-input v-model="checkRoleModule.name" :disabled="true" size="small"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="addRole.name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addRole.status" size="small" style="width: 100px"  placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="addRole.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="addRoleDialog = false" size="small">取 消</el-button>
      <el-button type="primary" @click="addRoleFun()" size="small">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog
        title="新增模块"
        :visible.sync="addRoleModuleDialog"
        width="40%"
        center
        :before-close="handleClose">
      <el-form ref="addRoleModule" :model="addRoleModule" :rules="rules" :label-width="labelWidth">
        <el-form-item label="模块名称" prop="name">
          <el-input v-model="addRoleModule.name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="模块顺序" prop="seq">
          <el-input type="number" v-model="addRoleModule.seq" size="small"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="addRoleModuleDialog = false" size="small">取 消</el-button>
      <el-button type="primary" @click="addRoleModuleFun()" size="small">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog
        title="新增子级模块"
        :visible.sync="addSonRoleModuleDialog"
        width="40%"
        center
        :before-close="handleClose">
      <el-form ref="addSonRoleModule" :model="addRoleModule" :rules="rules" :label-width="labelWidth">
        <el-form-item label="上级模块名称">
          <el-input v-model="checkRoleModule.name" size="small" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="模块名称" prop="name">
          <el-input v-model="addRoleModule.name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="模块顺序" prop="seq">
          <el-input type="number" v-model="addRoleModule.seq" size="small"></el-input>
        </el-form-item>
      </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addSonRoleModuleDialog = false" size="small">取 消</el-button>
      <el-button type="primary" @click="addSonRoleModuleFun" size="small">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog
        title="编辑模块"
        :visible.sync="editRoleModuleDialog"
        width="40%"
        center
        :before-close="handleClose">
      <el-form ref="editRoleModule" :model="editRoleModule" :rules="rules" :label-width="labelWidth">
        <el-form-item label="模块名称" prop="name">
          <el-input v-model="editRoleModule.name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="模块顺序" prop="seq">
          <el-input type="number" v-model="editRoleModule.seq" size="small"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editRoleModuleDialog = false" size="small">取 消</el-button>
    <el-button type="primary" @click="editRoleModuleFun" size="small">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
        title="编辑角色"
        :visible.sync="editRoleDialog"
        width="40%"
        center
        :before-close="handleClose">
      <el-form ref="editModule" :model="editRole" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editRole.name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea"  v-model="editRole.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editRoleDialog = false" size="small">取 消</el-button>
    <el-button type="primary" @click="editRoleFun" size="small">确 定</el-button>
  </span>
    </el-dialog>
    <el-drawer
        title="角色权限关系"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose"
        size="40%"
    >
      <el-tree
          ref="tree"
          :data="roleAclTree"
          show-checkbox
          check-strictly
          node-key="id"
          :default-expanded-keys="expanded"
          :default-checked-keys="checked"
          :props="roleAclProps">
      </el-tree>
      <el-button type="primary" size="small" @click="roleAclFun">提交</el-button>
    </el-drawer>
    <el-drawer
        title="角色用户关系"
        size="85%"
        :visible.sync="roleUserDrawer"
        :direction="direction"
        :before-close="handleClose">
      <el-transfer
          :props="{
            key: 'id',
            label: 'name'
          }"
          :titles="['未分配', '已分配']"
          :button-texts="['到左边', '到右边']"
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入用户名"
          v-model="checkedUsers"
          :data="allUserList">
        <span slot-scope="{ option }">{{ option.name }} - {{ option.telephone }}</span>
      </el-transfer>
      <el-button type="primary" size="mini" @click="updateRoleUserFun">保存</el-button>
    </el-drawer>
  </div>
</template>

<script>
import {getRoleByRoleModuleId,saveRole,updateRole,deleteRole,freezeRole} from '@/api/role/role'
import {getAllRoleModule,saveRoleModule,updateRoleModule,deleteRoleModule} from '@/api/role/roleModule'
import {getRoleAclTree,updateRoleAcl} from '@/api/role/roleAcl'
import {getRoleUser,updateRoleUser} from '@/api/role/roleUser'

// todo: 角色详情页

export default {
  name: "index",
  data() {
    return {
      labelWidth:'110px',
      filterRoleModuleText:'',
      editRoleDialog:false,
      editRole:{},
      checkedUsers:[],
      allUserList:[],
      roleUserDrawer:false,
      roleId:'',
      roleAclTree:{},
      checked:[],
      expanded:[],
      drawer: false,
      direction: 'rtl',
      addRole:{},
      checkRoleModule:{},
      addRoleModule:{},
      editRoleModule:{},
      page:{
        pageNo: 1,
        pageSize: 5,
        total: 1
      },
      addRoleDialog:false,
      editRoleModuleDialog:false,
      addSonRoleModuleDialog:false,
      addRoleModuleDialog:false,
      isCheck:false,
      roleData: [],
      roleModuleData: [],
      roleAclProps:{
        children: 'sonAclTreeDtoList',
        label: 'name',
        disabled:'noAcl'
      },
      defaultProps: {
        children: 'sonRoleModuleList',
        label: 'name'
      },
      options: [{
        value: '0',
        label: '冻结'
      }, {
        value: '1',
        label: '正常'
      }],
      rules: {
        name: [
          { required: true, message: '请输入模块名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        status:[
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        parentId:[
          {required: true, message: '请选择部门', trigger: 'blur'}
        ],
        seq: [
          { required: true,message: '请输入数字', trigger: 'blur'}
        ]
        ,remark: [
          { min: 0, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
      },
    };
  },
  created() {
    this.getRoleModuleTree();
  },
  watch: {
    filterRoleModuleText(val) {
      this.$refs.roleModuleTree.filter(val);
    }
  },
  methods: {
    filterRoleModuleNode(value, data){
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    editRoleFun(){
      updateRole(this.editRole).then(res =>{
        getRoleByRoleModuleId(this.page,this.checkRoleModule.id).then(res =>{
          this.roleData = res.data.records;
          this.page.total = res.data.total;
        })
        this.editRoleDialog = false;
      })
    },
    updateRoleUserFun(){
      // console.log(this.checkedUsers);
      updateRoleUser(this.roleId,{ids:this.checkedUsers}).then(res =>{
        this.roleUserDrawer = false;
      })
    },
    openRoleUserDrawer(row){
      getRoleUser(row.id).then(res =>{
        this.roleId = row.id;
        this.allUserList = res.data.allUserList;
        this.checkedUsers = res.data.checkedUsers;
        this.roleUserDrawer = true
      })

    },
    filterMethod(query, item) {
       return item.name.indexOf(query) > -1;
    },
    roleAclFun(){
      console.log(this.$refs.tree.getCheckedKeys());
      updateRoleAcl(this.roleId,{ids:this.$refs.tree.getCheckedKeys()}).then(res =>{
        this.drawer = false;
        this.roleId = '';
      })
    },
    openRoleAclTree(row){
      getRoleAclTree(row.id).then(res =>{
        this.roleId = row.id;
        this.drawer = true;
        this.roleAclTree = res.data.aclTree;
        this.checked = res.data.checkedAclIds;
      })
    },
    freezeRoleFun(index,row){
      let status = '0';
      if (row.status == '0'){
        status = '1';
      }
      freezeRole(row.id,status).then(res =>{
        getRoleByRoleModuleId(this.page,this.checkRoleModule.id).then(res =>{
          this.roleData = res.data.records;
          this.page.total = res.data.total;
        })
      })
    },
    delRoleFun(index,row){
      deleteRole(row.id).then(res =>{
        getRoleByRoleModuleId(this.page,this.checkRoleModule.id).then(res =>{
          this.roleData = res.data.records;
          this.page.total = res.data.total;
        })
      })
    },
    addRoleFun(){
      this.$refs['addRole'].validate((valid) => {
        if (!valid){
          return
        }
        this.addRole.parentId = this.checkRoleModule.id;
        saveRole(this.addRole).then(res =>{
          this.addRole = {};
          this.addRoleDialog = false;
          getRoleByRoleModuleId(this.page,this.checkRoleModule.id).then(res =>{
            this.roleData = res.data.records;
            this.page.total = res.data.total;
          })
        })
      });
    },
    addRoleModuleFun(){
      this.$refs['addRoleModule'].validate((valid) => {
        if (!valid){
          return
        }
        this.addRoleModule.parentId = '0';
        saveRoleModule(this.addRoleModule).then(res =>{
          this.addRoleModule = {};
          this.addRoleModuleDialog = false;
          this.getRoleModuleTree();
        })
      });

    },
    addSonRoleModuleFun(){
      this.$refs['addSonRoleModule'].validate((valid) => {
        if (!valid){
          return
        }
        this.addRoleModule.parentId = this.checkRoleModule.id;
        saveRoleModule(this.addRoleModule).then(res =>{
          this.addRoleModule = {};
          this.addSonRoleModuleDialog = false;
          this.getRoleModuleTree();
        })
      });
    },
    editRoleModuleFun(){
      this.$refs['editRoleModule'].validate((valid) => {
        if (!valid){
          return
        }
        updateRoleModule(this.editRoleModule).then(res =>{
          this.editRoleModule = {};
          this.editRoleModuleDialog = false;
          this.getRoleModuleTree();
        })
      });
    },
    getRoleModuleTree(){
      getAllRoleModule().then(res =>{
        this.roleModuleData = res.data
        this.isCheck =false;
      })
    },
    roleModuleDelFun(){
      if (!this.isCheck){
        open("请选择")
        return
      }
      deleteRoleModule(this.checkRoleModule.id).then(res =>{
        this.getRoleModuleTree();
      })
    },
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([3]);
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.page.pageNo = 1;
      getRoleByRoleModuleId(this.page,this.checkRoleModule.id).then(res =>{
        this.roleData = res.data.records;
        this.page.total = res.data.total;
      })
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      getRoleByRoleModuleId(this.page,this.checkRoleModule.id).then(res =>{
        this.roleData = res.data.records;
        this.page.total = res.data.total;
      })
      // console.log(`当前页: ${val}`);
    },
    stateFormat(row) {
      if (row.status == '0') {
        return '冻结'
      } else  {
        return '正常'
      }
    },
    handleNodeClick(data) {
      this.isCheck = true;
      this.checkRoleModule = data;
      this.editRoleModule = data;
      getRoleByRoleModuleId({pageNo:1,pageSize:5},data.id).then(res =>{
        this.roleData = res.data.records;
        this.page.total = res.data.total;
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    open(message) {
      this.$message({
        showClose: true,
        message: message,
        type: 'success'
      });
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.el-divider--vertical{
  height: 450px;
  vertical-align: text-top;
}
.box-card {
  width: 350px;
  height: 30px;
  margin: 5px 0px;
  background-color: #e6f7ff;
  padding: 0px;
  border: #1482f0;
}
.el-dialog .el-form .el-form-item .el-input{
  width: 80%;
}

</style>
